package alvarodelrosal.chat.client.modelo;

import alvarodelrosal.chat.client.gui.MainWindow;
import java.util.HashSet;
import java.util.Set;

public class Conversation {

    private int id;
    private String subject;
    private Set<ChatUser> users = new HashSet();
    private Set<Message> messages = new HashSet();

    public Conversation(int id, String subject) {
        this.id = id;
        this.subject = subject;
    }

    @Override
    public String toString() {
        return subject;
    }

    public int getId() {
        return id;
    }

    public String getSubject() {
        return subject;
    }
    
    public String getMessagesAsString() {
        StringBuilder builder = new StringBuilder();
        for(Message message : messages) {
            builder.append(message.getFrom().getName());
            builder.append(" dijo: ");
            builder.append(message.getText());
            builder.append("\n");
        }
        return builder.toString();
    }
    
    public ChatUser getUser(int userId) {
        for (ChatUser user : users) {
            if(user.getId() == userId) {
                return user;
            }
        }
        throw new IllegalArgumentException("El usuario solicitado no pertenece a este chat");
    }
    
    public void addMessage(Message message) {
        messages.add(message);
        MainWindow.updateChats();
    }
    
    public void addUser(ChatUser user) {
        users.add(user);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Conversation other = (Conversation) obj;
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 29 * hash + this.id;
        hash = 29 * hash + (this.subject != null ? this.subject.hashCode() : 0);
        hash = 29 * hash + (this.users != null ? this.users.hashCode() : 0);
        hash = 29 * hash + (this.messages != null ? this.messages.hashCode() : 0);
        return hash;
    }
    
}
